package cn.anecansaitin.whimsy.common.block;

import cn.anecansaitin.whimsy.common.block.entity.RockAltarEntity;
import cn.anecansaitin.whimsy.common.register.ModBlockEntities;
import net.minecraft.core.BlockPos;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.Nullable;

import java.util.Optional;

public class RockAltar extends Block implements EntityBlock {
    private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 2.5, 12);

    public RockAltar() {
        super(Properties.ofFullCopy(Blocks.GLASS));
    }

    @Override
    public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) {
        Optional<RockAltarEntity> blockEntity = level.getBlockEntity(pos, ModBlockEntities.ROCK_ALTAR.get());

        if (blockEntity.isEmpty()) {
            return InteractionResult.PASS;
        }

        RockAltarEntity rockAltarEntity = blockEntity.orElseThrow();
        return rockAltarEntity.exchangeItem(player, hand);
    }

    @Override
    public VoxelShape getShape(BlockState pState, BlockGetter pLevel, BlockPos pPos, CollisionContext pContext) {
        return SHAPE;
    }

    @Nullable
    @Override
    public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
        return new RockAltarEntity(pos, state);
    }

    @Nullable
    @Override
    public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level pLevel, BlockState pState, BlockEntityType<T> pBlockEntityType) {
        return (l, p, s, e) -> ((RockAltarEntity) e).tick(l, p, s);
    }

    @Override
    public void onRemove(BlockState state, Level level, BlockPos pos, BlockState newState, boolean movedByPiston) {
        BlockEntity blockEntity = level.getBlockEntity(pos);

        if (blockEntity instanceof RockAltarEntity r) {
            r.dropItem();
        }

        super.onRemove(state, level, pos, newState, movedByPiston);
    }
}
